
<template>
  <div style="width:600px;height: 600px;">
  <Codemirror v-model:value="code" :options="cmOptions" border ref="cmRef" height="900"  @change="onChange"
      @input="onInput" @ready="onReady">
  </Codemirror>
</div>
</template>
<script lang="ts" setup>
import {watch,ref,defineProps, onMounted, onUnmounted } from "vue"
// 导入的核心插件库
import "codemirror/mode/javascript/javascript.js"
// 核心组件
import Codemirror from "codemirror-editor-vue3"
// 主题
import "codemirror/theme/dracula.css";


// ts类型
import type { CmComponentRef } from "codemirror-editor-vue3"
import type { Editor, EditorConfiguration } from "codemirror"
import beautify from "js-beautify";
import mitt from '@/utils/mitt'
// 父传子的数据
let props=defineProps({
  selCode:{
    type:String,
    default:''
  }
})
// 从代码编辑器 v-model 绑定的值
const code = ref<any>('')
// 监听父传子的数据变化 从新赋值
watch(()=>props.selCode,(newVal)=>{
  code.value=beautify.js(newVal,{
    indent_size:2,//缩进大小，默认为 2。
  });
})




// 获取编辑器组件的ref
const cmRef = ref<CmComponentRef>()

// 编辑器配置项
const cmOptions: EditorConfiguration = {
  mode: "text/javascript", //代码类型
  theme: 'dracula',   // 设置你喜欢的主题  暗黑色
}
// 代码编辑器的change事件
const onChange = (val: string, cm: Editor) => {
  console.log(val)
  console.log(cm.getValue(),"----")
  // cm.getValue() 当前编辑器 最新的值
  // 传给兄弟组件
  mitt?.emit('codeChange',cm.getValue())
}

const onInput = (val: string) => {
  console.log(val)
}

const onReady = (cm: Editor) => {
  console.log(cm.focus())
}

onMounted(() => {
  setTimeout(() => {
      cmRef.value?.refresh()
  }, 1000)

  // setTimeout(() => {
  //     cmRef.value?.resize(300, 200)
  // }, 2000)

  setTimeout(() => {
      cmRef.value?.cminstance.isClean()
  }, 3000)
})

onUnmounted(() => {
  cmRef.value?.destroy()
})
</script>
